<template>
  <div class="mats-pane">
    <el-container>
      <el-header class="title-bar" height="auto">
        <el-row>
        <el-col :span="10">
        <!--
        <span class="title">{{ modeTitle }}</span>
        <span class="count">（{{ num }}/{{ totalCount }}）</span>
        -->
        <el-menu class="mode-menu" mode="horizontal" :default-active="modePath(mode)" @select="menuChanged">
          <el-menu-item index="fav">我的收藏<sub>（{{stats.fav}}）</sub></el-menu-item>
          <el-menu-item index="discover">衍星收录<sub>（{{stats.discover}}）</sub></el-menu-item>
          <el-menu-item index="resources">资源仓库<sub>（{{stats.resources}}）</sub></el-menu-item>
        </el-menu>
        </el-col>
        <el-col :span="14">
        <span class="right-bar">
          <el-divider direction="vertical"></el-divider>
          <sorter class="sorter" :options="sortOptions" v-model="orderby" @change="orderChanged()"></sorter>
        </span>
        <span class="right-bar">
          <el-input v-model="keyword" size="mini" class="search-input" placeholder="搜索" @change="searchMats">
            <template #prepend><el-button icon="el-icon-search" @click="searchMats"></el-button></template>
            <template #append>
              <el-select v-model="searchType" @change="changeSearchType">
                <el-option label="标题" value="t"></el-option>
                <el-option label="内容" value="c"></el-option>
                <el-option label="作者" value="a"></el-option>
              </el-select>
            </template>
          </el-input>
          <el-button type="warning" size="mini" icon="el-icon-refresh" @click="randomMats" >{{fav ? '随机' : '推荐'}}</el-button>
          <el-button type="primary" size="mini" icon="el-icon-circle-plus" @click="addMat" >添加</el-button>
        </span>


        </el-col>
        </el-row>
      </el-header>
      <el-main>
        <scroller height="84vh">
        <div class="book-list">
          <div class="book-item-wrap" v-for="(p, i) in mats" :key="i">
            <mat-card :mat="p" @edit-tags="editTags"></mat-card>
          </div>
          <div id="pageLoader" class="book-list-pager">
            <el-button v-if="showHasMore" @click="loadMore()">加载更多...</el-button>
          </div>
          <div class="notice" v-if="num == 0 && !showResources">
            暂无收藏，请前往
            <a href="/#/poems/discover">衍星收录</a>
            或
            <a href="/#/poems/resources">资源仓库</a>
            寻找你喜欢的诗词
          </div>
        </div>
        </scroller>
      </el-main>
      <edit-tags :tags="tags" :cats="cats" :kind="MatKind.Poem" :mat="mat" v-model="tagsDialogVisible"></edit-tags>
    </el-container>

    <div></div>
  </div>
</template>

<script>
import MatCard from "../mats/MatCard"
import EditTags from "../mats/EditTags"
import Scroller from "@/tools/Scroller"
import Sorter from "@/tools/Sorter"
import { TagCat, MatKind, PoemMode, NoteScope, NoteKind } from '@/js/constants'

export default {
  props: ["mode"],
  components: {
    MatCard,
    EditTags,
    Scroller,
    Sorter,
  },
  watch: {
    mode() {
      this.clear();
      this.fetchMats();
    }
  },
  data() {
    return {
      MatKind: MatKind,
      PoemMode: PoemMode,
      showResources: false,
      stats: {
        fav: 0,
        discover: 0,
        resources: 0
      },
      resourceSearch: "",
      filter: null,
      mats: [],
      totalCount: 0,
      limit: 10,
      offset: 0,
      orderby: this.fav ? 'f' : 't',
      keyword: '',
      searchType: 't',
      random: false,
      sortOptions: [{
        value: 'f',
        label: '按收藏时间'
      }, {
        value: 't',
        label: '按时间'
      }, {
        value: 'n',
        label: '按名称'
      }, {
        value: 'h',
        label: '按热度'
      }, {
        value: 's',
        label: '按星量'
      }],
      mat: {},
      tags: [],
      cats: [TagCat.Genre, TagCat.Era, TagCat.Style, TagCat.Tune, TagCat.Rhyme],
      tagsDialogVisible: false,
    };
  },
  computed: {
    num() {
      return this.mats.length;
    },
    showHasMore() {
      if (this.random) return false;
      return this.totalCount > this.mats.length;
    },
    fav() {
      return this.mode == PoemMode.Fav;
    },
    isResource() {
      return this.mode == PoemMode.Resources;
    },
    modeTitle() {
      switch(this.mode) {
        case PoemMode.Fav:
          return "我的收藏";
        case PoemMode.Discover:
          return "衍星收录";
        case PoemMode.Resources:
          return "资源仓库";
        default:
          return "我的收藏";
      }
    },
  },
  created() {
    this.fetchStats();
    // 初始化诗歌列表
    this.fetchMats();
    // TODO: 添加默认搜索条件
    // EVENT_BUS.$on("poems-filter", (f) => {
    //   this.clear()
    //   this.filter = f;
    //   this.fetchMats();
    // });
  },
  methods: {
    modePath(index) {
      switch(index) {
        case PoemMode.Fav:
          return "fav";
        case PoemMode.Discover:
          return "discover";
        case PoemMode.Resources:
          return "resources";
        default:
          return "fav";
      }
    },
    changeSearchType() {
      if (this.keyword != "") {
        this.searchMats();
      }
    },
    menuChanged(index) {
      let path = "/poems/" + index;
      if (path != this.$route.path) {
        this.$router.push(path);
      } else {
        this.clear();
        this.searchMats();
      }
    },
    fetchStats() {
      this.authGet("/api/v1/mats/poems/stats").then(res => {
        this.stats = res.data;
      });
    },
    clear() {
      this.totalCount = 0;
      this.limit = 10;
      this.offset = 0;
      this.orderby = this.fav ? 'f': 't';
      this.random = false;
      this.filter = null;
      this.keyword = "";
      //this.mats = [];
    },
    editTags(mat) {
      this.tags = mat.tags || [];
      this.mat = mat;
      this.tagsDialogVisible = true;
    },
    randomMats() {
      this.clear();
      this.random = true;
      this.fetchMats();
    },
    searchMats() {
      let keyword = this.keyword;
      this.clear();
      this.keyword = keyword;
      this.fetchMats();
    },
    orderChanged() {
      this.mats = [];
      this.fetchMats();
    },
    loadMore() {
      let loader = document.getElementById("pageLoader");
      loader.style = "display: none;";
      this.offset += this.limit;
      this.fetchMats(true);
    },
    fetchMats(isAppend) {
      let s = "?";
      s += "limit="+this.limit + "&offset=" + this.offset;
      if (this.filter) {
        if (this.filter.kind == "author") {
          s = s + "&author=" + this.filter.value.id;
        } else if (this.filter.kind == "tag") {
          s = s + "&tag=" + this.filter.value.id;
        }
      }
      s += "&o=" + this.orderby;
      if (this.random) {
        s += "&r=1"
      }
      if (s == "?") s = "";
      
      if (this.keyword) {
        s += "&k=" + this.keyword;
        s += "&st=" + this.searchType;
      }

      if (this.mode == PoemMode.Fav) {
        this.authGet("/api/v1/mats/poems/fav" + s)
          .then((res) => { 
            if (isAppend) {
              this.appendMats(res.data);
            } else {
              this.resetMats(res.data);
            }
          })
          .catch((err) => { console.log("error getting mats: " + err); });
      } else {
        let url = "";
        if (this.mode == PoemMode.Discover) {
          url = "/api/v1/mats/poems/search"; 
        } else {
          url = "/api/v1/mats/resources/search"; 
        }
        this.$axios
          .get(url + s)
          .then((res) => {
            if (isAppend) {
              this.appendMats(res.data);
            } else {
              this.resetMats(res.data);
            }
          })
          .catch((err) => { console.log("error getting poems: " + err); });
      }
    },
    processMats(mats) {
      let ms = mats;
      ms.forEach((m) => {
        if (m.star === undefined) {
          m.star = {
            mid: m.id,
            kind: NoteKind.Star,
            scope: NoteScope.Article,
            value: 0,
          };
        }
        // 将标签按照类别和名称排序
        if (m.tags) {
          m.tags.sort((x, y) => x.cat - y.cat != 0 ? x.cat - y.cat : x.val - y.val);
        } else {
          m.tags = [];
        }
      });
      return ms;
    },
    resetMats(data) {
      console.log("resetting mats")
      this.totalCount = data.total;
      this.mats = this.processMats(data.mats);
      this.loadStars();
    },
    appendMats(data) {
      console.log("appending mats")
      this.totalCount = data.total;
      let ms = this.processMats(data.mats);
      this.mats = this.mats.concat(ms);
      this.loadStars();
      // 再次显示”加载更多“按钮。这么做是为了不让滚动条直接跳到新加载的末尾
      let loader = document.getElementById("pageLoader");
      loader.style = "display: block;";
    },
    loadStars() {
      let ids = this.mats.map((p) => p.id);
      this.authPost("/api/v1/note/mystars/material", ids).then((res) => {
        let stars = res.data;
        let smap = {};
        for (let star of stars) {
          let mid = star.mid;
          smap[mid] = star;
        }
        for (let p of this.mats) {
          if (p.id in smap) {
            let star = smap[p.id];
            p.star = star;
          }
        }
      });
    },
    addMat() {
      this.$router.push("/poems/edit");
    },
  },
};
</script>

<style lang="stylus">
.mats-pane
  text-align left
  padding 0

  .title-bar
    line-height 4.5vh
    .mode-menu
      .el-menu-item
        height auto
        min-height 4.5vh
        line-height 4.5vh
        font-size 1em
        font-weight bold
        padding 0 0.4vw

        sub
          font-weight normal

    .search-input
      width 15vw
      .el-input-group__prepend
        padding 0 0.6vw
      .el-input-group__append
        width 2vw
        padding 0 0.9vw

  >.el-container>.el-main
    padding 1vh 1vw 0 1vw

  .book-list-pager
    text-align center

  .book-list>.notice
    margin-top 50px
    text-align center

  .title-bar
    .count
      color #999

    .el-input
      margin-right 10px

  .book-item-wrap
    display block
</style>